package ch07.shizhang;

import ch07.shizhang.SysUser;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class RequestToPojo<T> {
    public static <T> T convertTojo(Map<String, String[]> parameterMap, Class<T> clazz) throws InstantiationException, IllegalAccessException {
        //
        T t = clazz.newInstance();
        // 1.迭代Map取出key对应实体对象的属性名，value对应属性值
        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
            String key = entry.getKey();
            String[] value = entry.getValue();

            // 将value转换为字符串，如果value数组不为空，取第一个值
            if (value.length > 0) {
                String fieldValue = value[0];

                try {
                    // 2.获取属性，并设置值
                    Field field = clazz.getDeclaredField(key);
                    // 允许访问私有字段
                    field.setAccessible(true);
                    // 自动根据类型进行转换
                    if (field.getType() == String.class) {
                        field.set(t, fieldValue);
                    } else if (field.getType() == int.class || field.getType() == Integer.class) {
                        field.set(t, Integer.parseInt(fieldValue));
                    }
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                }
            }
        }
        return t;
    }

    public static void main(String[] args) throws InstantiationException, IllegalAccessException {
        Map<String, String[]> parameterMap = new HashMap<>();
        parameterMap.put("realName", new String[]{"张三"});

        SysUser sysUser = RequestToPojo.convertTojo(parameterMap, SysUser.class);
        System.out.println(sysUser.getRealName());

        Map<String, String[]> parameterMap1 = new HashMap<>();
        parameterMap1.put("constact", new String[]{"李四"});

        Address address = RequestToPojo.convertTojo(parameterMap1, Address.class);
        System.out.println(address.getConstact());
    }
}
